// /**
//  * @file server.prod.js
//  * @author lavas
//  */

// var LavasCore = require('lavas-core-vue');
// var express = require('express');
// var app = express();

// var port = process.env.PORT || 3000;

// var core = new LavasCore(__dirname);

// process.env.NODE_ENV = 'production';

// core.init(process.env.NODE_ENV)
//     .then(function () {
//         core.runAfterBuild()
//     })
//     .then(function () {
//         app.use(core.expressMiddleware());
//         app.listen(port, function () {
//             console.log('server started at localhost:' + port);
//         });
//     }).catch(function (err) {
//         console.log(err);
//     });

// // catch promise error
// process.on('unhandledRejection', function (err, promise) {
//     console.log('in unhandledRejection');
//     console.log(err);
//     // cannot redirect without ctx!
// });

var express = require('express')
var path = require('path')
var app = express()
var http = require('http')
var bodyParser = require('body-parser')
var debug = require('debug')('app:server')
var proxyMiddleware = require('http-proxy-middleware')
var config = {
  build: {
    port: 8585,
    proxyTable: {
      '/nodeProxy': {
        target: 'https://api-dev.boqii.com/api/v1.1',
        changeOrigin: true,
        pathRewrite: {
          '/nodeProxy': '/'
        }
      }
    },
    assetsRoot: path.resolve(__dirname, './dist')
  }
}

var port = config.build.port

// proxy api requests
var proxyTable = config.build.proxyTable

// proxy api requests
Object.keys(proxyTable).forEach(function (context) {
  var options = proxyTable[context]
  if (typeof options === 'string') {
    options = {
      target: options
    }
  }
  app.use(proxyMiddleware(options.filter || context, options))
})

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
  extended: false
}))

// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
  extended: false
}))

// handle fallback for HTML5 history API
app.use(require('connect-history-api-fallback')());
app.use(express.static(config.build.assetsRoot))

var port = config.build.port
app.set('port', port)

/**
 * Create HTTP server.
 */

var server = http.createServer(app)

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port)
// server.on('error', onError);
server.on('listening', onListening)

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address()
  var bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port
  debug('Listening on ' + bind)
}
